import { Form, Input } from 'antd-mobile';
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'umi';
import styles from './index.less';
import { throttle } from 'lodash';

interface ValidateCodeProps {
  time: number;
  getValidate: () => boolean | Promise<boolean>;
}

let timer: any;

export default function (props: ValidateCodeProps) {
  const { time, getValidate } = props;
  let [count, setCount] = useState(0);
  function decrease() {
    timer = setInterval(function () {
      setCount((count) => {
        if (count - 1 == 0) {
          clearInterval(timer);
          timer = null;
        }
        return count - 1;
      });
    }, 1000);
  }
  const queryValidate = useCallback(
    throttle(function () {
      if (timer) {
        return;
      }
      const result = getValidate();
      if (result instanceof Promise) {
        result.then((value) => {
          if (value) {
            setCount(time);
            decrease();
          }
        });
      } else if (result) {
        setCount(time);
        decrease();
      }
    }, 300),
    [getValidate, time],
  );

  return (
    <Form.Item
      layout="horizontal"
      name="code"
      label="验证码"
      rules={[{ required: true, message: '验证码不能为空' }]}
      extra={
        <div
          onClick={count > 0 ? undefined : queryValidate}
          className={count > 0 ? styles.hasCode : styles.getCode}
        >
          {count > 0 ? `${count}s` : '获取验证码'}
        </div>
      }
    >
      <Input placeholder="请输入验证码" />
    </Form.Item>
  );
}
